var API = require('API');
agGrid.initialiseAgGridWithAngular1(angular);


var app = angular.module('sales', ['ngAnimate', 'ngRoute', 'agGrid'])


    .controller("HomeController", require('HomeController'))
    .controller("UserController", require('UserController'))
    .controller("RoleController", require('RoleController'))
    .controller("RanksController", require('RanksController'))
    .controller("PrivilegesController", require('PrivilegesController'))
    .controller("ShopController", require('ShopController'))
    .controller("ShopSorterController", require('ShopSorterController'))
    .controller("ShopUserController", require('ShopUserController'))

    .directive('datetimepicker', require('angular-datetimepicker'))
    .directive('checkboxes', require('angular-checkboxes'))
    .directive('userPicker', require('angular-userpicker'))
    .directive('shopPicker', require('angular-shoppicker'))
    .directive('memberShopPicker', require('angular-member-shoppicker'))
    .directive('vmInput', require('angular-vehiclemodelinput'))
    //.directive('vmPicker', require('angular-vehiclemodelpicker'))
    .directive('salesmanPicker', require('angular-salesmanpicker'))
    .directive('evaluatorPicker', require('angular-evaluatorpicker'))
    .directive('vehicleDemoPicker', require('angular-vehicledemopicker'))
    .directive('sorter', require('angular-sorter'))
    .directive('filter', require('angular-filter'))

    //directive-forms
    .directive('userInc', require('user-inc'))
    .directive('shopInc', require('shop-inc'))

    .config(['$routeProvider', '$locationProvider',
        function ($routeProvider, $locationProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider
                .when('/index.html', {
                    templateUrl: "/views/home.html",
                    controller: 'HomeController'
                })
                .when('/', {
                    templateUrl: "/views/home.html",
                    controller: 'HomeController'
                })
                .when('/users', {
                    templateUrl: "views/users.html",
                    controller: 'UserController'
                })
                .when('/shops', {
                    templateUrl: "views/shops.html",
                    controller: 'ShopController'
                })
                .when('/shop_sorter', {
                    templateUrl: "views/shop_sorter.html",
                    controller: 'ShopSorterController'
                })
                .when('/roles', {
                    templateUrl: "views/roles.html",
                    controller: 'RoleController'
                })
                .when('/shop_user', {
                    templateUrl: "views/shop_user.html",
                    controller: 'ShopUserController'
                })
                .when('/ranks', {
                    templateUrl: "views/ranks.html",
                    controller: 'RanksController'
                })
                .when('/privileges', {
                    templateUrl: "views/privileges.html",
                    controller: 'PrivilegesController'
                })


                .when('/import', {
                    templateUrl: 'views/import.html',
                    controller: 'SalesImportController'
                })

                // admin
                .when('/admin/users', {
                    templateUrl: '/modules/admin/users/users.html',
                    controller: require('users_ctrl')
                })
                .when('/admin/privileges', {
                    templateUrl: '/modules/admin/privileges/privileges.html',
                    controller: require('privileges_ctrl')
                })
                .when('/admin/ranks', {
                    templateUrl: '/modules/admin/ranks/ranks.html',
                    controller: require('ranks_ctrl')
                })
                .when('/admin/shops', {
                    templateUrl: '/modules/admin/shops/shops.html',
                    controller: require('shops_ctrl')
                })
                .when('/admin/shop_user', {
                    templateUrl: '/modules/admin/shop_user/shop_user.html',
                    controller: require('shop_user_ctrl')
                })

                .when('/admin/set_user', {
                    templateUrl: '/modules/admin/set_user/set_user.html',
                    controller: require('set_user_ctrl')
                })

                .when('/customer_service/question', {
                    templateUrl: '/modules/customer_service/question/question.html',
                    controller: require('question_ctrl')
                })
                .when('/customer_service/temp', {
                    templateUrl: '/modules/customer_service/temp/temp.html',
                    controller: require('temp_ctrl')
                })
                .when('/customer_service/temp_display/:id', {
                    templateUrl: '/modules/customer_service/temp/temp_display.html',
                    controller: require('temp_display_ctrl')
                })
                .when('/customer_service/order', {
                    templateUrl: '/modules/customer_service/order/order.html',
                    controller: require('order_ctrl')
                })
                .when('/customer_service/order_display/:id', {
                    templateUrl: '/modules/customer_service/order/order_display.html',
                    controller: require('order_display_ctrl')
                })
                .otherwise({
                    templateUrl: "/404.html"
                })
        }])
    .factory("loginServ", ['$q', function ($q) {

        var cache_user = void 0;
        var cache_roles = void 0;

        var t = {

            async_validate_role: function (role_id) {
                var d = $q.defer();
                t.user().then(function (user) {
                    var found = user._roles
                            .filter(function (x) {
                                return x.id == role_id
                            })
                            .length > 0;
                    d.resolve(found);
                });
                return d.promise;
            },

            validate_role: function (role_id) {
                if (cache_roles) {
                    //console.log('user', user, user._roles);
                    var found = cache_roles
                            .filter(function (x) {
                                return x.id == role_id
                            })
                            .length > 0;
                    return found;
                }
                else {
                    // console.warn("cache_roles null, need async?");
                    return false;
                }
            },

            user: function () {
                var deferred_user = $q.defer();
                if (cache_user) {
                    deferred_user.resolve(cache_user);
                } else
                    API.sys.login_user(function (user) {
                        t.roles(user.id).then(function (roles) {
                            user._roles = roles.filter(function (x) {
                                return x.rolename.startsWith('R')
                            });
                            if (user._shop)

                                deferred_user.resolve(cache_user = user);
                        });
                    });

                return deferred_user.promise;
            },

            roles: function (user) {

                var deferred_roles = $q.defer();
                if (cache_roles) {
                    deferred_roles.resolve(cache_roles);
                } else
                    API.rbac.roles_for_user(user, function (roles) {
                        deferred_roles.resolve(cache_roles = roles);
                    });

                return deferred_roles.promise;
            },


            menu: function () {
                //if (cache_menu) {
                //    deferred_menu.resolve(cache_menu);
                //} else
                var deferred_menu = $q.defer();
                API.sys.menu(function (menu) {
                    //cache_menu = menu;
                    deferred_menu.resolve(menu);
                });

                return deferred_menu.promise;
            }
        };
        return t;
    }])
    .run(['$rootScope', 'loginServ', '$location', '$route',
        function ($rootScope, loginServ, $location, $route) {
            // var view_shops;
            loginServ.menu().then(function (data) {

                $rootScope.menu = data;
                var path = $location.path();
                var result = $rootScope.menu.find(function (m) {
                    return m.href == path
                });
                $rootScope.title = result ? result.rolename : '';
                $rootScope.menu[current_menu].icon = true;
            });

            //TODO 做成service
            loginServ.user().then(function (user) {
                if (user) {
                    $rootScope.user = user;
                }
            });

            //test_factory.fu();
            var current_menu = 0;

            $rootScope.open_module = function (item, index) {

                $rootScope.menu[current_menu].icon = false;
                current_menu = index || 0;
                // console.log('item.href',item.href);
                item.icon = true;
                $rootScope.title = item.name || item.rolename;
                $rootScope.toggle_help = (sessionStorage.getItem("toggle_help") == 'true');

                //save the search states
                if (item.search
                    && Object.keys(item.search).length > 0
                    && JSON.stringify(item.search) != JSON.stringify($location.search())
                ) {
                    // console.log('using $routeUpdate', JSON.stringify(item.search), JSON.stringify($location.search()));
                    $location.search(item.search).replace();

                    if (item.href) {
                        $rootScope.$on('$routeUpdate', function (event, route) {
                            // console.log('$route Update!', arguments);
                            $location.path(item.href).search(item.query || {});
                        });
                    }
                }
                else {
                    // console.log('using normal routing');
                    if (item.href) {
                        $location.path(item.href);
                    }
                    $location.search(item.query || {});
                }
                //console.log('$location',$location);
            };

            $rootScope._today = new Date();
            $rootScope.toggle_help = (sessionStorage.getItem("toggle_help") == 'true');

            $('.help-doc').css({display: $rootScope.toggle_help ? "block" : "none"});

            $rootScope.$watch('toggle_help', function (val, old) {
                // console.log('watch toggle_help', val);
                //if(val !== undefined && val != old )
                //$('.help-doc').css({display:Boolean(val)?"block":"none"});
                sessionStorage.setItem("toggle_help", val);
            });

            $rootScope.validate_role = loginServ.validate_role;

            $rootScope.me_data_submit = function () {
                API.user.upd($rootScope.user, function () {
                    alert("修改成功！");
                })
            };

        }]);

(function (app) {

})(app);
